package com.azt.front.action.index;

import com.azt.api.dto.CartListData;
import com.azt.api.dto.CartProduct;
import com.azt.api.dto.PushEnquiryListDto;
import com.azt.api.dto.item.ProductExt;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.front.action.BaseAction;
import com.azt.front.permission.RequireUser;
import com.azt.front.utils.ContextUtil;
import com.azt.front.utils.Globals;
import com.azt.model.AjaxJson;
import com.azt.utils.CommonUtil;
import com.azt.utils.CookieUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *   ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　＞　　　＜　┃
 * ┃　　　　　　　┃
 * ┃...　⌒　...　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 *     ┃　　　┃　
 *     ┃　　　┃
 *     ┃　　　┃
 *     ┃　　　┃  神兽保佑
 *     ┃　　　┃  代码无bug　　
 *     ┃　　　┃
 *     ┃　　　┗━━━┓
 *     ┃　　　　　　　┣┓
 *     ┃　　　　　　　┏┛
 *     ┗┓┓┏━┳┓┏┛
 *       ┃┫┫　┃┫┫
 *       ┗┻┛　┗┻┛
 */
@Controller
public class IndexAction extends BaseAction {

	@Autowired
	private UserService userService;

	@Autowired
	private AreaService areaService;

	@Autowired
	private ProCategoryService proCategoryService;

	@Autowired
	private EnqEnquiryService enquiryService;

	@Autowired
	private EnqQuoteService quoteService;

	@Autowired
	private CompanyCategoryService companyCategoryService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private ContentService contentService;

	@Autowired
	private RecommendBrandService recommendBrandService;

	@Autowired
	private RecommendCompanyService recommendCompanyService;

	@Autowired
	private UserVisitService userVisitService;

	@Autowired
	private ProductService productService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private CompanySignService companySignService;

	@RequestMapping("/")
	public String begin(Model model) {
		//询价单数量
		model.addAttribute("enquiryCount", enquiryService.getIndexEnquiryCount());
		//入驻企业
		model.addAttribute("userCount", userService.getIndexUserCount());
		//平台交易量
		model.addAttribute("totalPrice", orderService.getIndexOrderPrice()/10000);
		//最新询价单
		model.addAttribute("enquiryList", enquiryService.findIndexEnquiry(ContextUtil.getCompanyId(), 6));
		//最新成交
		model.addAttribute("orderList", orderService.findIndexOrder(7));
		//集采品牌
		model.addAttribute("brandList", recommendBrandService.findIndexBrand());
		//名企推荐
		model.addAttribute("companyList", CommonUtil.splitList(recommendCompanyService.findIndexCompany(), 5));
		//资讯
		model.addAttribute("newsList1", contentService.findIndexNews("INDUSTRY_NEWS", 6));//行业资讯
		model.addAttribute("newsList2", contentService.findIndexNews("HI_TECH", 6));		//新产品新技术
		model.addAttribute("newsList3", contentService.findIndexNews("BIG_EVENT", 6));		//平台大事件
		return "index";
	}

	@RequestMapping("/index")
	public String index() {
		return "redirect:/";
	}

	/**
	 * 项目汇
	 * */
	@RequestMapping("/xmh")
	public String xmh(Model model) {
		//产品分类
		List<Category> categoryList = proCategoryService.findTopCategory();
		//地区
		List<Area> areaList = areaService.findChinaAreas();

		model.addAttribute("categoryList", categoryList);
		model.addAttribute("areaList", areaList);
		return "xmh/xmh";
	}

	@RequestMapping("/xmh/{enquiryId}")
	public String xmhDetail(@PathVariable Integer enquiryId, Model model) {
		EnqEnquiry enquiry = enquiryService.getEnquiryById(enquiryId);

		/*if(enquiry == null || enquiry.getState().intValue() != EnqEnquiryEnum.ENQ_POSTED.getIndex() || enquiry.getState().intValue() != EnqEnquiryEnum.ENQ_OVER.getIndex()) {
			return "/error/404";
		}*/

		List<EnqEnquiryItem> itemList = enquiryService.getEnquiryItem(enquiryId);

		int quoteNum = quoteService.getQuoteNum(enquiryId);

		Company company = companyService.getTopParentCompany(enquiry.getCustomerId());
		List<CompanyCategory> categoryList = companyCategoryService.findCategoryByCompanyId(company.getId());
		CompanyInfo companyInfo = companyService.selectByCompanyIdDetail(company.getId());

		boolean hasQuote = false;
		if(ContextUtil.getCompany() != null) {
			//hasQuote = enquiryService.hasQuote(ContextUtil.getCompany().getId(), enquiryId) || ContextUtil.getCompanyId().equals(enquiry.getCustomerId());
			//只有自己公司的人才能看到联系信息
			hasQuote = ContextUtil.getCompanyId().equals(enquiry.getCustomerId());
		}

		model.addAttribute("hasQuote", hasQuote);
		model.addAttribute("categoryList", categoryList);
		model.addAttribute("company", company);
		model.addAttribute("companyInfo", companyInfo);
		model.addAttribute("itemList", itemList);
		model.addAttribute("quoteNum", quoteNum);
		model.addAttribute("enquiry", enquiry);
		model.addAttribute("pages", CommonUtil.getPageCount(itemList.size(), 10));

		//记录访问记录
		userVisitService.recordVisit(ContextUtil.getUserId(), enquiryId, "enquiry");
		return "xmh/detail";
	}

	/**
	 * 项目汇：是否能参与报价
	 * */
	@ResponseBody
	@RequestMapping("/canQuote")
	public AjaxJson canQuote() {
		Integer enquiryId = getParaToInt("enquiryId");
		if(enquiryId != null) {
			AjaxJson aj = enquiryService.canQuote(ContextUtil.getUser(), ContextUtil.getRoles(), ContextUtil.getCompany(), ContextUtil.getCurrentRole(), enquiryId);
			return aj;
		}
		return AjaxJson.error("该询价不允许报价");
	}

	/**
	 * 项目汇搜索
	 * @param categorySId 产品分类
	 * @param qtype 需求类型
	 * @param hasQuote 有无报价
	 * @param area 地区
	 * @param startPubDate 发布开始时间
	 * @param endPubDate 发布结束时间
	 * @param startDeadline 截止开始时间
	 * @param endDeadline 截止结束时间
	 * @param hasAttach 是否有附件
	 * @param sort 排序
	 * @param paraNo 当前页码
	 * @param showSize 每行显示数量
	 * @param rowSize 每页显示行数
	 * */
	@ResponseBody
	@RequestMapping(value = "/searchXmh", method = RequestMethod.POST)
	public AjaxJson searchXmh() {
		Map param = WebUtils.getParametersStartingWith(request, null);
		param.put("companyId", ContextUtil.getCompany() != null ? ContextUtil.getCompany().getId() : null);
		//处理开始结束时间
		Date startPubDate = CommonUtil.safeToDate(getPara("startPubDate"), "yyyy-MM-dd");
		Date endPubDate = CommonUtil.safeToDate(getPara("endPubDate"), "yyyy-MM-dd");
		Date startDeadline = CommonUtil.safeToDate(getPara("startDeadline"), "yyyy-MM-dd");
		Date endDeadline = CommonUtil.safeToDate(getPara("endDeadline"), "yyyy-MM-dd");
		param.put("startPubDate", startPubDate);
		param.put("endPubDate", endPubDate != null ? DateUtil.offsetDay(endPubDate, 1) : null);
		param.put("startDeadline", startDeadline);
		param.put("endDeadline", endDeadline != null ? DateUtil.offsetDay(endDeadline, 1) : null);

		int pageNo = getParaToInt("pageNo", 1);		//当前页码
		int showSize = getParaToInt("showSize", 4);	//每行显示数量
		int rowSize = getParaToInt("rowSize", 4);	//每页显示行数

		String sort = getPara("sort");
		if(StrUtil.isNotBlank(sort)) {
			PageHelper.orderBy(sort);
		} else {
			PageHelper.orderBy("if(enq.state = 1, 1, 0) desc,enq.id desc");
		}
		Page page = PageHelper.startPage(pageNo, showSize * rowSize);
		List<Map> list = enquiryService.searchXmh(param);

		for(Map map : list) {
			Integer customerId = Convert.toInt(map.get("customerId"));
			String enquiryName = Convert.toStr(map.get("enquiryName"));
			String companyName = Convert.toStr(map.get("companyName"));
			String pCompanyName = Convert.toStr(map.get("pCompanyName"));
			String ppCompanyName = Convert.toStr(map.get("ppCompanyName"));
			Integer hasQuoteNum = Convert.toInt(map.get("hasQuoteNum"));		//该公司的报价次数

			if(ContextUtil.getCompanyId() != null && ContextUtil.getCompanyId().equals(customerId)) {
				//不隐藏询价信息
			} else {
				map.put("companyName", CommonUtil.getHiddenStr(companyName, 5));
				map.put("pCompanyName", CommonUtil.getHiddenStr(pCompanyName, 5));
				map.put("ppCompanyName", CommonUtil.getHiddenStr(ppCompanyName, 5));
				map.put("enquiryName", CommonUtil.getSimpleStr(enquiryName, 30));
				map.put("logo", null);
				map.put("pLogo", null);
				map.put("ppLogo", null);
			}
		}

		Map map = new HashMap();
		map.put("data", CommonUtil.splitList(list, showSize));
		map.put("pages", page.getPages());		//总页数
		map.put("total", page.getTotal());			//总数
		return AjaxJson.success().setAttributes(map);
	}


	/**
	 * 项目汇详情页查询关注单位
	 * @param enquiryId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/focusCompanys", method = RequestMethod.POST)
	public AjaxJson getFocusCompanys(Integer enquiryId) {

		int pageNo = getParaToInt("pageNo", 1);		//当前页码
		int pageSize = getParaToInt("pageSize", 5);	//显示数量
		int orderDown = getParaToInt("orderDown", 0);	//关注排序

		List<Map> list = null;
		Page page = PageHelper.startPage(pageNo, pageSize);
		if(enquiryId != null){
			list =enquiryService.getFocusCompanys(enquiryId , orderDown);
		}

		Map map = new HashMap();
		map.put("data", list);
		map.put("orderDown", orderDown);
		map.put("contentSize", list.size());
		map.put("totalPages", page.getPages());		//总页码
		map.put("currentPage", page.getPageNum());		//当前页码
		return AjaxJson.success().setAttributes(map);
	}


	/**
	 * 获取最新发布
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getNewPush", method = RequestMethod.POST)
	public AjaxJson getNewPush() {

		int pageSize = getParaToInt("pageSize", 5);	//显示数量

		Integer companyId = ContextUtil.getCompany() != null ? ContextUtil.getCompany().getId() : null;
		List<PushEnquiryListDto> list = enquiryService.getNewPush(companyId , pageSize);
		if(companyId != null && CollectionUtil.isEmpty(list)) {
			//没有最新发布数据的话则获取游客的最新发布数据
			list = enquiryService.getNewPush(null , pageSize);
		}
		for(PushEnquiryListDto pushEnquiry : list) {
			String companyName = pushEnquiry.getCompanyName();
			String pCompanyName = pushEnquiry.getParentCompany();
			String ppCompanyName = pushEnquiry.getPpCompany();
			String enquiryName = pushEnquiry.getEnquiryName();

			if(ContextUtil.getCompanyId() != null && ContextUtil.getCompanyId().equals(pushEnquiry.getCustomerId())) {
				//只有本公司的人看才不隐藏信息
			} else {
				pushEnquiry.setLogo(null);
				pushEnquiry.setCompanyName(CommonUtil.getHiddenStr(companyName, 5));
				pushEnquiry.setParentCompany(CommonUtil.getHiddenStr(pCompanyName, 5));
				pushEnquiry.setPpCompany(CommonUtil.getHiddenStr(ppCompanyName, 5));
				pushEnquiry.setEnquiryName(CommonUtil.getSimpleStr(enquiryName, 10));
			}
		}

		Map map = new HashMap();
		map.put("data", list);
		return AjaxJson.success().setAttributes(map);
	}

	/**
	 * 购物车
	 * */
	@RequireUser
	@RequestMapping("/cart")
	public String cart() {
		return "order/cart";
	}

	@RequireUser
	@RequestMapping(value = "/cart/success/{skuId}")
	public String addCartSuccess(@PathVariable("skuId") Integer skuId, Model model) {
		List<CartProduct> list = productService.findCartProduct(skuId + "");
		if(CollectionUtil.isNotEmpty(list)) {
			CartProduct product = list.get(0);
			Double realPrice = productService.calcProductPrice(skuId, ContextUtil.getCompanyId());
			product.setRealPrice(realPrice);
			model.addAttribute("product", product);
			List<ProductExt> productExts = productService.guessYouLike(productService.getProductById(product.getProductId()).getCategoryTId());
			model.addAttribute("list", productExts);
			model.addAttribute("count", CommonUtil.getPageCount(productExts.size(), 5));
			return "order/addCartSuccess";
		}
		return "order/addCartSuccess";
	}

	/**
	 * 获取购物车列表
	 * */
	@ResponseBody
	@RequireUser
	@RequestMapping(value = "/listCart", method = RequestMethod.POST)
	public AjaxJson listCart() {
		List<Map> cartList = ContextUtil.getCartCookie();
		if(CollectionUtil.isEmpty(cartList)) {
			return AjaxJson.error();
		}

		boolean isSigned = companySignService.getCompanySign(ContextUtil.getCompanyId(), 2, true) != null;
		List<CartListData> cartListDatas = productService.parseCartData(cartList, isSigned);

		if(CollectionUtil.isNotEmpty(cartListDatas)) {
			return AjaxJson.success().setObj(cartListDatas);
		} else {
			//当cookie有值但是cartListDatas无数据的时候，可能是cookie中的值有问题，将cookie清空
			CookieUtils.deleteCookie(request, response, Globals.CART_COOKIE);
			return AjaxJson.error();
		}
	}

	@RequestMapping("/azt/msgcount")
	@ResponseBody
	public AjaxJson list(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		AjaxJson j = new AjaxJson();
		User user = ContextUtil.getUser();
		//int msgNOReadCount = alertMsgService.getMsgNOReadCount(user.getId(), user.getEntry());
		//j.setObj(msgNOReadCount);
		return j;
	}
	
	
	@RequestMapping("/azt/enquiry/new")
	public String azt(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		model.put("username", ContextUtil.getUser().getEmail());
		
		return "enquiry/enquiry_list";
	}

	@RequestMapping("/mq")
	public String mq(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		return "index";
	}

	@RequestMapping("/validate")
	@ResponseBody
	public boolean checkValidate(HttpServletRequest request , String code){
		return ContextUtil.checkImageVerificationCode(code);
	}

	/**
	 * @Description 省市区查询
	 * @param code
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/querycityBycode")
	public List<Area> querycityBycode(String code, String id){
		if(StringUtils.isNoneBlank(code)){
			return areaService.getAreaByParentCode(code);
		}else if(StringUtils.isNoneBlank(id)){
			return areaService.getAreaByParentId(Integer.parseInt(id));
		}
		return null;
	}

	/**
	 * @Description 企业资料里面查询开户行
	 * @param areaCode
	 * @param bankCode
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryOpenBank")
	public List<Map> queryOpenBank(String areaCode,String bankCode){
		return (areaCode != null && bankCode != null ) ? companyService.getOpenBank(areaCode, bankCode) : null;
	}
	
	
	

	@RequireUser
	@ResponseBody
	@RequestMapping(value = "/sendTestMail")
	public void sendTestMail(HttpServletRequest request, HttpServletResponse response, Model model) {
		/*String[] array = {"7ippy@163.com", "1075894724@qq.com", "wll@azt365.com", "wesley1992@sina.cn"};

		for(String email : array) {
			userService.sendActiveMail(email, UUID.randomUUID().toString());
			userService.sendIforgotMail(email, UUID.randomUUID().toString());
		}*/
	}

	@RequestMapping(value = "/wqq/{dir}/{file}")
	public String wqq(@PathVariable("dir") String dir, @PathVariable("file") String file) {
		return "demo/" + dir + "/" + file;
	}
	
	@RequestMapping(value = "/file")
	public String fileManager(){
		return "demo/fileManager";
	}

	@RequestMapping(value = "/enquiryDemo")
	public String enquiryDemo(){
		return "demo/enquiryDemo";
	}

	@RequestMapping("/noperm")
	public String noperm() {
		return "error/nopermission";
	}
	
	@RequestMapping("/shangwenqiang/{to}")
	public String swq(@PathVariable("to") String to, HttpServletRequest request , HttpServletResponse response , Model model){
		return "demo/shangwenqiang/" + to;
	}
	@RequestMapping("/zhoudd/{to}")
	public String zdd(@PathVariable("to") String to, HttpServletRequest request , HttpServletResponse response , Model model){
		return "demo/zhoudd/" + to;
	}
}
